
let conf = {
    iceServers: [
        {
            urls: `stun:stun.l.google.com:19302`,
            username: '',
            credential: ''
        }
    ],
    iceTransportPolicy: 'all',
    bundlePolicy: 'max-bundle',
    rtcpMuxPolicy: 'require',
    sdpSemantics: 'unified-plan'
};


let peerConnection = new RTCPeerConnection(conf);
let localStream;

let init= async () => {
    localStream = await navigator.mediaDevices.getUserMedia({video:true, audio:false})
    document.getElementById('user-1').srcObject = localStream

    localStream.getTracks().forEach((track) =>{
        peerConnection.addTrack(track,localStream);
    })

    document.getElementById("create-offer").addEventListener('click',createOffer)
    document.getElementById('add-answer').addEventListener('click',addAnswer)
    document.getElementById('add-ice').addEventListener('click',addICE)
}

let createOffer=async () =>{
    peerConnection.onicecandidate = async (event) =>{
        if(event.candidate)
        {
            document.getElementById('offer-sdp').value = JSON.stringify(peerConnection.localDescription);
            document.getElementById('gen-ice').value = JSON.stringify(event.candidate);
        }
    }
    
    let offer = await peerConnection.createOffer();
    console.log(offer);
    await peerConnection.setLocalDescription(offer);

    document.getElementById('offer-sdp').value = JSON.stringify(peerConnection.localDescription);

}

let addAnswer = async()=>{
    let answer = JSON.parse(document.getElementById('answer-sdp').value)
    if(!peerConnection.currentRemoteDescription)
    {
        peerConnection.setRemoteDescription(answer);
        console.log("set remote sdp suceee");
    }
}

let addICE = async()=>{
    let ice = JSON.parse(document.getElementById('ice').value)
    peerConnection.addIceCandidate(ice);
    console.log("add ICE candidate:"+ice);
}



init()

